<?php

namespace app\admin\model\xilujob;

use app\admin\model\User;
use app\common\library\Auth;
use fast\Random;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_except;

class XilujobUser extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'xilujob_user';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'actiontime_text',
        'source_text'
    ];

    const GROUP_MEMBER = '1';// 求职用户
    const GROUP_COMPANY = '2';// 企业

    const SOURCE_REGISTER = '0'; //注册
    const SOURCE_BACKEND = '1'; //后台添加
    //const SOURCE_BACKEND_ONLY_RESUME = '2'; //后台添加简历, 用户数据无用
    //const SOURCE_SHARE_LOGIN = '3'; //简历、自助登记用户
    

    
    public function getSourceList()
    {
        return ['0' => __('Source 0'), '1' => __('Source 1')];
    }


    public function getActiontimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['actiontime']) ? $data['actiontime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getSourceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source']) ? $data['source'] : '');
        $list = $this->getSourceList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id','id',[],'INNER')->setEagerlyType(0);
    }


    /**
     *新增用户
     * @param string $group , in: ['1','2','3','4']
     * @param $userData
     * @param $enterpriseData
     * @param array $modelData
     * @param array $user_data
     * @return string|Model
     * @throws \think\exception\DbException
     */
    public static function add_user($group, $userData, $enterpriseData, $modelData=[],$user_data=[]) {
        $mobile = $userData['mobile'] ?? null;
        $email =  $userData['email'] ?? null;
        if(!$mobile && !$email) {
            throw new Exception('手机号和邮箱，必填一项');
        }
        $userData['jointime'] = time();
        //如果用户不存在，新增
        if(!$user_data){
            $validator = new \app\admin\validate\User();

            $validator->scene('add', ['username', 'password', 'email', 'mobile']);

            if(!$validator->scene('add')->check($userData)) {
                throw new Exception($validator->getError());
            }
            $user = new \app\common\model\User();

            $password = !empty($userData['password'])?$userData['password']:Random::alnum();
            $userData['salt'] = Random::alnum();
            $userData['password'] = (new Auth())->getEncryptPassword($password, $userData['salt']);
            $userData['status'] = 'normal';
            $ret = $user->save($userData);
            if($ret===false) {
                throw new Exception($user->getError());
            }
        }else{
            $password = !empty($userData['password'])?$userData['password']:Random::alnum();
            $userData['salt'] = Random::alnum();
            $userData['password'] = (new Auth())->getEncryptPassword($password, $userData['salt']);
            $userData['status'] = 'normal';
            $ret = $user_data->save($userData);
        }

        switch ($group) {
            case 1:
                $groupModel = new Member();
                break;
            case 2:
                $groupModel = new CompanyProfile();
                break;
//            case 3:
//                $groupModel = new LabourShop();
//                break;
//            case 4:
//                $groupModel = new Trainer();
//                break;
            default:
                throw new Exception('参数错误');
        }
        #对应用户身份表数据
        $xiluuserModel = new XilujobUser();
        if(!$user_data){
            $xiluuserData['user_id'] = $user_data?$user_data['id']:$user->id;
            $xiluuserData['group_id'] = $group;
            $xiluuserData['source'] = XilujobUser::SOURCE_BACKEND;

            $ret = $xiluuserModel->save($xiluuserData);
            if($ret===false) {
                throw new Exception($xiluuserModel->getError());
            }
        }
        $modelData['user_id'] = $user_data?$user_data['id']:$user->id;

        if($group != 1){
            if(get_addon_config('xilujob')['enterprise_audit_switch']) {
                $modelData['audit_status'] = \app\common\model\xilujob\CompanyProfile::ENTERPRISE_AUDIT_STATUS_WAITING;
            }else {
                //自动过审
                $modelData['audit_status'] = \app\common\model\xilujob\CompanyProfile::ENTERPRISE_AUDIT_STATUS_PASSED;
            }
        }
        $ret = $groupModel->save($modelData);
        if($ret===false) {
            throw new Exception($groupModel->getError());
        }

        #企业组数据添加
        if($group != 1) {
            $enterpriseData['user_id'] = $user_data?$user_data['id']:$user->id;
            $enterpriseData['company_id'] = $groupModel->id;
//            if($group== self::GROUP_TRAINER) {
//                $xiluuserModel->save(['trainer_group_id'=>$group]);
//            }else {
                if(!$user_data){
                    $xiluuserModel->save(['enterprise_group_id' => $group]);
                }else{
                    $xiluuserModel->where('user_id',$user_data['id'])->update(['enterprise_group_id' => $group]);
                }
//            }
            if(empty($enterpriseData['company_name']) && $enterpriseData['full_name']){
                $enterpriseData['company_name'] = $enterpriseData['full_name'];
            }else if(!empty($enterpriseData['company_name']) && empty($enterpriseData['full_name'])){
                $enterpriseData['full_name'] = $enterpriseData['company_name'];
            }
            $enterpriseInfo = EnterpriseInfo::create(array_except($enterpriseData,['benefit_ids']));
            $enterpriseInfo = \app\common\model\xilujob\EnterpriseInfo::get($enterpriseInfo->id);
            \app\common\model\xilujob\EnterpriseInfo::saveInfo($enterpriseInfo, array_intersect_key($enterpriseData, array_flip(['benefit_ids'])));
        }
        return $groupModel;
    }


    public static function edit_user($id, $group, $userData, $enterpriseData, $modelData=[]) {
        $mobile = $userData['mobile'] ?? null;
        $email = $userData['email'] ?? null;
        if(!$mobile && !$email) {
            throw new Exception('手机号和邮箱，必填一项');
        }

        $user = User::get($id);
        $userData =  array_intersect_key($userData, array_flip((array) ['mobile','email','username','password','nickname','avatar','status']));

        $validator = new \app\admin\validate\User([
            'mobile'=>['regex:^1[3456789]\d{9}$','unique:user,mobile,'.$id],
            'email' => ['email','unique:user,email,'.$id],
        ]);

        $validator->scene('edit', ['mobile','email']);

        if(!$validator->scene('edit')->check($userData)) {
            throw new Exception($validator->getError());
        }

        $ret = $user->save($userData);
        //halt($ret);
        if($ret===false) {
            throw new Exception($user->getError());
        }
        if($modelData) {
            switch ($group) {
                case 1:
                    $groupModel = Member::get(['user_id'=>$id]);
                    break;
                case 2:
                    $groupModel = CompanyProfile::get(['user_id'=>$id]);
                    break;
//                case 3:
//                    $groupModel = LabourShop::get($id);
//                    break;
//                case 4:
//                    $groupModel = Trainer::get($id);
//                    break;
                default:
                   throw new Exception('参数错误');
            }
            $xiluuserModel = XilujobUser::get(['user_id'=>$id]);
            #对应用户身份表数据更新
            $xiluuserData['user_id'] = $user->id;
            $xiluuserData['group_id'] = $group;
            $xiluuserData['source'] = XilujobUser::SOURCE_BACKEND;
            $ret = $xiluuserModel->save($xiluuserData);
            if ($ret === false) {
                throw new Exception($xiluuserModel->getError());
            }

            $name = str_replace("\\model\\", "\\validate\\", get_class($groupModel));
            $ret = $groupModel->validate($name . '.edit')->save($modelData);

            if ($ret === false) {
                throw new Exception($groupModel->getError());
            }
        }
        if($group!=1) {
            $enterpriseInfo = EnterpriseInfo::get(['user_id'=>$user->id]);
            if(!empty($enterpriseData['company_name'])){
                $enterpriseData['full_name'] = $enterpriseData['company_name'];
            }
            $enterpriseInfo->save(array_except($enterpriseData,['benefit_ids']));
            \app\common\model\xilujob\EnterpriseBenefit::save_info($enterpriseInfo, array_intersect_key($enterpriseData, array_flip((array) ['benefit_ids'])));
        }
        return true;
    }

}
